package cn.highedu.coolsharkhub.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
public class UploadDemoController {
    private Logger logger = LoggerFactory.getLogger(UploadDemoController.class);

    /**
     * 文件上传 请求路径/upload 和前端页面的action一致
     * @param imageFile 代表文件 参数名必须和前端页面中表单的name一致
     * @return 文件存储的路径
     */
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public String upload(MultipartFile imageFile) {
        //File storagePath = new File("D:/upload");
        //本地测试
        File storagePath = new File("/Users/liucangsong/coolsharkhub/upload");
        // 获取文件名
        String filename = imageFile.getOriginalFilename();
        // 创建文件存储路径
        if (!storagePath.exists()) {
            storagePath.mkdirs();
        }
        // 保存文件
        try {
            imageFile.transferTo(new File(storagePath, filename));
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
        // 返回文件存储路径
        return filename;
    }

}
